﻿using System;
using System.IO;
using System.Net;

namespace USElections.Utils
{
    public class BitLyUrlShortener
    {
        private const string username = "__your username__";
        private const string api = "__your api key__";

        public static void Execute(string url, Action<string> completed)
        {
            string requestUrl = string.Format(@"http://api.bit.ly/v3/shorten?login={0}&apiKey={1}&longUrl={2}&format=txt", username, api, HttpUtility.UrlEncode(url));
            try
            {
                WebClient wc = new WebClient();
                wc.OpenReadCompleted += (sender, e) =>
                {
                    string shortenedUrl = string.Empty;

                    try
                    {
                        Stream stream = e.Result;
                        StreamReader reader = new StreamReader(stream);
                        shortenedUrl = reader.ReadToEnd();
                    }
                    catch (Exception ex)
                    {
                    }

                    if (completed != null)
                    {
                        completed(shortenedUrl);
                    }

                };

                wc.OpenReadAsync(new Uri(requestUrl));
            }
            catch (Exception ex)
            {
                if (completed != null)
                {
                    completed(string.Empty);
                }
            }

        }
    }
}
